package cn.sell.mbg.crm.user.service.Impl;

import cn.sell.comm.base.MySqlCrudServiceImpl;
import cn.sell.mbg.crm.user.UmsUser;
import cn.sell.mbg.crm.user.service.UmsUserService;
import cn.sell.mbg.crm.user.view.UserInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

import java.util.List;

@Log4j2
@Service
@Transactional
public class UmsUserServiceImpl extends MySqlCrudServiceImpl<UmsUser, Long> implements UmsUserService {

    @Override
    public UmsUser login(UmsUser umsUser) throws Exception {
        List<UmsUser> umsUsers = super.selectByEntity(umsUser);
        if (umsUsers != null && umsUsers.size() == 1) {
            return umsUsers.get(0);
        }
        return null;
    }

    @Override
    public UmsUser register(UmsUser umsUser) throws Exception {
        Condition condition = new Condition(UmsUser.class);
        condition.createCriteria().andEqualTo("phone", umsUser.getPhone());

        UmsUser user = new UmsUser();
        user.setPhone(umsUser.getPhone());
        List<UmsUser> umsUsers = super.selectByCondition(condition);
        if (umsUsers.size() != 0) {
            throw new Exception("手机号已经注册，请勿重新注册");
        }
        umsUser.setStatus(umsUser.getStatus() == null ? 0 : umsUser.getStatus());
        umsUser.setId(super.insert(umsUser));
        return umsUser;
    }

    @Override
    public UmsUser updateByPhone(UmsUser umsUser) throws Exception {
        Condition condition = new Condition(UmsUser.class);
        condition.createCriteria().andEqualTo("phone", umsUser.getPhone());
        UmsUser user = new UmsUser();
        user.setPhone(umsUser.getPhone());
        log.info(umsUser.getPhone());
        List<UmsUser> umsUsers = super.selectByCondition(condition);
        if (umsUsers.size() != 0) {
            user.setId(umsUsers.get(0).getId());
            user.setPassword(umsUser.getPassword());
            super.updateByPkSelective(umsUsers.get(0).getId(), user);
            return user;
        } else {
            throw new Exception("手机号尚未注册，请您注册账号！！");
        }
    }

    @Override
    public UserInfo userInfo(Long userId) {
        UserInfo userInfo = new UserInfo();
        UmsUser umsUser = super.selectByPk(userId);
        userInfo.setUmsUser(umsUser);
        return userInfo;
    }
}
